package org.example.struct.array2;

/**
 * @author liyishan
 * @date 2023/10/7 09:14
 * @apiNote
 */

public class Test00189Rotate {

    public void test1(int[] nums, int k) {
        int n = nums.length;
        int[] newArr = new int[n];
        for (int i = 0; i < n; i++) {
            newArr[(i + k) % n] = nums[i];
        }
        System.arraycopy(newArr, 0, nums, 0, n);
    }


    public void test2(int[] nums, int k) {
        int n = nums.length;
        k = k % n;
        int count = 0;
        for (int start = 0; count < n; start++) {
            int cur = start;
            int pre = nums[cur];
            do{
                int next = (cur + k) % n;
                int temp = nums[next];
                nums[next] = pre;
                pre = temp;
                cur = next;
                count ++;
            }while(start != cur);
        }
    }


    /**
     * 3次反转
     * 1 2 3 4 5 6 7    3   ===》  5 6 7 1 2 3 4
     * 7 6 5 4 3 2 1
     * 5 6 7 4 3 2 1
     * 5 6 7 1 2 3 4
     *
     * @param nums
     * @param k
     */
    public void test3(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }

    public void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start += 1;
            end -= 1;
        }
    }

}
